package com.butterfly.hotkey.worker.framework.component;


import com.butterfly.hotkey.core.cache.CacheFactory;
import com.butterfly.hotkey.core.cache.ICacheManager;
import com.butterfly.hotkey.core.model.AppCacheModel;
import com.butterfly.hotkey.worker.framework.properties.WorkerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.butterfly.hotkey.core.constant.NumConst.FIVE;
import static com.butterfly.hotkey.worker.constants.WorkerConst.DEFAULT_HOT_KEY_INIT_SIZE;
import static com.butterfly.hotkey.worker.constants.WorkerConst.DEFAULT_HOT_KEY_MAX_SIZE;

/**
 * 构建worker中的缓存器
 *
 * @author butterfly
 */
@Configuration
public class CacheConfig {

    /**
     * 存放所有hotkey的缓存
     * 当key热的时候，存放一份
     * 缓存存在时，worker就不用继续判断是否过热了，因为client端会将数据放入本地缓存中了
     *
     * @param workerProperties workerProperties
     * @return hotKeyCache
     */
    @Bean("hotKeyCache")
    public ICacheManager hotKeyCache(WorkerProperties workerProperties) {
        AppCacheModel recent = workerProperties.getCacheRecent();
        if (recent == null) {
            recent = AppCacheModel.Builder.builder()
                    .initialCapacity(DEFAULT_HOT_KEY_INIT_SIZE)
                    .maximumSize(DEFAULT_HOT_KEY_MAX_SIZE)
                    .build();
        }

        // 5s基本也一定推送出去了
        return CacheFactory.buildCache(recent, FIVE);
    }

}
